<?php
	/**
	 +=========================================================
	 * 后台管理公共常用类
	 * CommonAction
	 +=========================================================
	 * @copyright © 2011 nickdraw.com All rights reserved.
	 * @author NickDraw(零度温柔) webmaster@206c.net
	 * @license http://www.nickdraw.com/license
	 +=========================================================
	 */
	class CommonAction extends Action 
	{
		protected static $model = null; //数据模型model
		protected $arc_model = null;
		protected $theme;
		protected $items;
		public $lang = 'zh-cn';
		public $sessionID;
		public $userID;
		public $userInfo;
		
		function _initialize()
		{
			header("Content-type: text/html; charset=utf-8");
			// 用户权限检查
			if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
				import ( '@.ORG.RBAC' );
				if (! RBAC::AccessDecision ()) {
					//检查认证识别号
					if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
						if ($this->isAjax()){ 
							$this->ajaxReturn(true, "", 301);
						} else {
							//跳转到认证网关
							$this->redirect ( C('USER_AUTH_GATEWAY') );
						}
					}
					// 没有权限 抛出错误
					if (C ( 'RBAC_ERROR_PAGE' )) {
						// 定义权限错误页面
						$this->redirect ( C ( 'RBAC_ERROR_PAGE' ) );
					} else {
						if (C ( 'GUEST_AUTH_ON' )) {
							$this->assign ( 'jumpUrl', U( C('USER_AUTH_GATEWAY') ) );
						}
						// 提示错误信息
						$this->error ( L ( '_VALID_ACCESS_' ) );
					}
				}
			}
			
			//检查语言
			if ( isset( $_COOKIE['think_language'] ) ){
				$this->lang = strtolower($_COOKIE['think_language']);
			}
	    }
		
		/**
	     +----------------------------------------------------------
		 * 取得操作成功后要返回的URL地址
		 * 默认返回当前模块的默认操作
		 * 可以在action控制器中重载
	     +----------------------------------------------------------
		 * @access public
	     +----------------------------------------------------------
		 * @return string
	     +----------------------------------------------------------
		 * @throws ThinkExecption
	     +----------------------------------------------------------
		 */
		function getReturnUrl() {
			if (isset($_GET['tag'])){
				//return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' ) . '&tag=' . $_GET['tag'];
				return U(C ( 'DEFAULT_ACTION' ),array('tag'=>$_GET['tag']));
			}else{
				//return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
				return U(C ( 'DEFAULT_ACTION' ));
			}
		}
		
		public function index() {
			//列表过滤器，生成查询Map对象
			$map = $this->_search();
	        if (method_exists($this, '_filter')) {
	            $this->_filter($map);
	        }
	        $model = M($this->getActionName());
	        if (!empty($model)) {
	            $this->_list($model, $map);
	        }
	        $this->display();
	        return;
		}
		
		/**
	      +----------------------------------------------------------
	     * 验证码显示
	      +----------------------------------------------------------
	     * @access public
	      +----------------------------------------------------------
	     * @return void
	      +----------------------------------------------------------
	     * @throws FcsException
	      +----------------------------------------------------------
	     */
	    function verify() {
	        import("ORG.Util.Image");
	        Image::buildImageVerify();
	    }
		
		/**
	     +----------------------------------------------------------
		 * 根据表单生成查询条件
		 * 进行列表过滤
	     +----------------------------------------------------------
		 * @access protected
	     +----------------------------------------------------------
		 * @param string $name 数据对象名称
	     +----------------------------------------------------------
		 * @return HashMap
	     +----------------------------------------------------------
		 * @throws ThinkExecption
	     +----------------------------------------------------------
		 */
		protected function _search($name = '') {
			//生成查询条件
			if (empty($name)) {
	            $name = $this->getActionName();
	        }
	        $model = M($name);
	        $map = array();
	        foreach ($model->getDbFields() as $key => $val) {
	            if (substr($key, 0, 1) == '_')
	                continue;
	            if (isset($_REQUEST[$val]) && $_REQUEST[$val] != '') {
	                $map[$val] = $_REQUEST[$val];
	            }
	        }
	        return $map;
		}
		
		/**
	     +----------------------------------------------------------
		 * 根据表单生成查询条件
		 * 进行列表过滤
	     +----------------------------------------------------------
		 * @access protected
	     +----------------------------------------------------------
		 * @param Model $model 数据对象
		 * @param HashMap $map 过滤条件
		 * @param string $sortBy 排序
		 * @param boolean $asc 是否正序
	     +----------------------------------------------------------
		 * @return void
	     +----------------------------------------------------------
		 * @throws ThinkExecption
	     +----------------------------------------------------------
		 */
		protected function _list($model, $map = array(), $sortBy = '', $asc = false) {
	        //排序字段 默认为主键名
	        if (isset($_REQUEST['_order'])) {
	            $order = $_REQUEST['_order'];
	        } else {
	            $order = !empty($sortBy) ? $sortBy : $model->getPk();
	        }
	        //排序方式默认按照倒序排列
	        //接受 sost参数 0 表示倒序 非0都 表示正序
	        if (isset($_REQUEST['_sort'])) {
	            $sort = $_REQUEST['_sort'] ? 'asc' : 'desc';
	        } else {
	            $sort = $asc ? 'asc' : 'desc';
	        }
	        //取得满足条件的记录数
	        $count = $model->where($map)->count('id');
	        import("ORG.Util.Page");
	        //创建分页对象
	        if (!empty($_REQUEST['listRows'])) {
	            $listRows = $_REQUEST['listRows'];
	        } else {
	            $listRows = '';
	        }
	        $p = new Page($count, $listRows);
	        //分页查询数据
	        $list = $model->where($map)->order($order . ' ' . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
	        //分页跳转的时候保证查询条件
	        foreach ($map as $key => $val) {
	            if (!is_array($val)) {
	                $p->parameter .= '&' .$key. '=' . urlencode($val);
	            }
	        }
	
	        //分页显示
	        $page = $p->show();
	        //列表排序显示
	        $sortImg = $sort;                                   //排序图标
	        $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列';    //排序提示
	        $sort = $sort == 'desc' ? 1 : 0;                     //排序方式
	        //模板赋值显示
	        $this->assign('list', $list);
	        $this->assign('sort', $sort);
	        $this->assign('order', $order);
	        $this->assign('sortImg', $sortImg);
	        $this->assign('sortType', $sortAlt);
	        $this->assign("page", $page);
	        Cookie::set('_currentUrl_', __SELF__);
	        return;
		}
	    
	    function insert() {
			$model = D($this->getActionName());
	        if (false === $model->create()) {
	            $this->error($model->getError());
	        }
	        //保存当前数据对象
	        if ($result = $model->add()) { //保存成功
	            // 回调接口
	            if (method_exists($this, '_tigger_insert')) {
	                $model->id = $result;
	                $this->_tigger_insert($model);
	            }
	            //成功提示
	            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
	            $this->success(L('新增成功'));
	        } else {
	            //失败提示
	            $this->error(L('新增失败'));
	        }
		}
	
		public function add() {
			$this->display ();
		}
	
		function read() {
			$this->edit ();
		}
	
		function edit() {
			$model = M($this->getActionName());
	        $id = $_REQUEST[$model->getPk()];
	        $vo = $model->find($id);
	        $this->assign('vo', $vo);
	        $this->display();
		}
	
		function update() {
			$model = D($this->getActionName());
	        if (false === $model->create()) {
	            $this->error($model->getError());
	        }
	        // 更新数据
	        if (false !== $model->save()) {
	            // 回调接口
	            if (method_exists($this, '_tigger_update')) {
	                $this->_tigger_update($model);
	            }
	            //成功提示
	            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
	            $this->success(L('更新成功'));
	        } else {
	            //错误提示
	            $this->error(L('更新失败'));
	        }
		}
		
		/**
	     * 默认列表选择操作
	     *
	     * @access public
	     * @return string
	     * @throws FcsException
	     */
	    protected function select($fields = 'id,name', $title = '') {
	        $map = $this->_search();
	        //创建数据对象
	        $Model = M($this->getActionName());
	        //查找满足条件的列表数据
	        $list = $Model->where($map)->getField($fields);
	        $this->assign('selectName', $title);
	        $this->assign('list', $list);
	        $this->display();
	        return;
	    }
		
		
		/**
	     +----------------------------------------------------------
		 * 默认删除操作
	     +----------------------------------------------------------
		 * @access public
	     +----------------------------------------------------------
		 * @return string
	     +----------------------------------------------------------
		 * @throws ThinkExecption
	     +----------------------------------------------------------
		 */
		public function delete() {
			//删除指定记录
			$model = M($this->getActionName());
	        if (!empty($model)) {
	            $pk = $model->getPk();
	            $id = $_REQUEST[$pk];
	            if (isset($id)) {
	                $condition = array($pk => array('in', explode(',', $id)));
	                if (false !== $model->where($condition)->delete()) {
	                    $this->success(L('删除成功'));
	                } else {
	                    $this->error(L('删除失败'));
	                }
	            } else {
	                $this->error('非法操作');
	            }
	        }
		}
		
		// 通过审核
	    public function pass() {
	        //删除指定记录
	        $model = D($this->getActionName());
	        if (!empty($model)) {
	            $pk = $model->getPk();
	            if (isset($_REQUEST[$pk])) {
	                $id = $_REQUEST[$pk];
	                $condition = array($pk => array('in', explode(',', $id)));
	                if (false !== $model->where($condition)->setField('status', 1)) {
	                    $this->assign("jumpUrl", $this->getReturnUrl());
	                    $this->success('审核通过！');
	                } else {
	                    $this->error('审核失败！');
	                }
	            } else {
	                $this->error('非法操作');
	            }
	        }
	    }
	    
	    /**
	     +----------------------------------------------------------
		 * 默认禁用操作
		 *
	     +----------------------------------------------------------
		 * @access public
	     +----------------------------------------------------------
		 * @return string
	     +----------------------------------------------------------
		 * @throws FcsException
	     +----------------------------------------------------------
		 */
		public function forbid() {
			$model = D($this->getActionName());
	        $pk = $model->getPk();
	        $id = $_GET[$pk];
	        $condition = array($pk => array('in', $id));
	        if ($model->forbid($condition)) {
	            $this->assign("jumpUrl", $this->getReturnUrl());
	            $this->success('状态禁用成功！');
	        } else {
	            $this->error('状态禁用失败！');
	        }
		}
		
		public function recycle() {
			$model = D($this->getActionName());
	        $pk = $model->getPk();
	        $id = $_GET[$pk];
	        $condition = array($pk => array('in', $id));
	        if ($model->recycle($condition)) {
	            $this->assign("jumpUrl", $this->getReturnUrl());
	            $this->success('状态还原成功！');
	        } else {
	            $this->error('状态还原失败！');
	        }
		}
	
		public function recycleBin() {
			$map = $this->_search();
	        $map['status'] = -1;
	        $model = D($this->getActionName());
	        if (!empty($model)) {
	            $this->_list($model, $map);
	        }
	        $this->display();
		}
		
		// 检查是否是当前作者
	    protected function checkAuthor($name = '') {
	        if ($_SESSION[C('USER_AUTH_KEY')] != 1) {
	            $id = $_GET['id'];
	            $name = empty($name) ? $this->getActionName() : $name;
	            $Model = M($name);
	            $Model->find((int) $id);
	            if ($Model->member_id != $_SESSION[C('USER_AUTH_KEY')]) {
	                $this->error('没有权限！');
	            }
	        }
	    }
	    
	    /**
	     +----------------------------------------------------------
		 * 默认恢复操作
		 *
	     +----------------------------------------------------------
		 * @access public
	     +----------------------------------------------------------
		 * @return string
	     +----------------------------------------------------------
		 * @throws FcsException
	     +----------------------------------------------------------
		 */
		function resume() {
			//恢复指定记录
			$model = D($this->getActionName());
	        $pk = $model->getPk();
	        $id = $_GET[$pk];
	        $condition = array($pk => array('in', $id));
	        if ($model->resume($condition)) {
	            $this->assign("jumpUrl", $this->getReturnUrl());
	            $this->success('状态恢复成功！');
	        } else {
	            $this->error('状态恢复失败！');
	        }
		}
		
		function recommend() {
	        $model = D($this->getActionName());
	        $pk = $model->getPk();
	        $id = $_GET[$pk];
	        $condition = array($pk => array('in', $id));
	        if ($model->recommend($condition)) {
	            $this->assign("jumpUrl", $this->getReturnUrl());
	            $this->success('推荐成功！');
	        } else {
	            $this->error('推荐失败！');
	        }
	    }
	
	    function unrecommend() {
	        $model = D($this->getActionName());
	        $pk = $model->getPk();
	        $id = $_GET[$pk];
	        $condition = array($pk => array('in', $id));
	        if ($model->unrecommend($condition)) {
	            $this->assign("jumpUrl", $this->getReturnUrl());
	            $this->success('取消推荐成功！');
	        } else {
	            $this->error('取消推荐失败！');
	        }
	    }
	    
	    function saveTag($tags, $id, $module = MODULE_NAME) {
	        if (!empty($tags) && !empty($id)) {
	            $Tag = M("Tag");
	            $Tagged = M("Tagged");
	            // 记录已经存在的标签
	            $exists_tags = $Tagged->where("module='{$module}' and record_id={$id}")->getField("id,tag_id");
	            $Tagged->where("module='{$module}' and record_id={$id}")->delete();
	            $tags = explode(' ', $tags);
	            foreach ($tags as $key => $val) {
	                $val = trim($val);
	                if (!empty($val)) {
	                    $tag = $Tag->where("module='{$module}' and name='{$val}'")->find();
	                    if ($tag) {
	                        // 标签已经存在
	                        if (!in_array($tag['id'], $exists_tags)) {
	                            $Tag->where('id=' . $tag['id'])->setInc('count');
	                        }
	                    } else {
	                        // 不存在则添加
	                        $tag = array();
	                        $tag['name'] = $val;
	                        $tag['count'] = 1;
	                        $tag['module'] = $module;
	                        $result = $Tag->add($tag);
	                        $tag['id'] = $result;
	                    }
	                    // 记录tag关联信息
	                    $t = array();
	                    $t['user_id'] = Session::get(C('USER_AUTH_KEY'));
	                    $t['module'] = $module;
	                    $t['record_id'] = $id;
	                    $t['create_time'] = time();
	                    $t['tag_id'] = $tag['id'];
	                    $Tagged->add($t);
	                }
	            }
	        }
	    }
		
		function saveSort() {
			$seqNoList = $_POST ['seqNoList'];
			if (! empty ( $seqNoList )) {
				//更新数据对象
			$name=$this->getActionName();
			$model = D ($name);
				$col = explode ( ',', $seqNoList );
				//启动事务
				$model->startTrans ();
				foreach ( $col as $val ) {
					$val = explode ( ':', $val );
					$model->id = $val [0];
					$model->sort = $val [1];
					$result = $model->save ();
					if (! $result) {
						break;
					}
				}
				//提交事务
				$model->commit ();
				if ($result!==false) {
					//采用普通方式跳转刷新页面
					$this->success ( '更新成功' );
				} else {
					$this->error ( $model->getError () );
				}
			}
		}
		
		// 查看某个模块的标签相关的记录
	    public function tag() {
	        $Tag = M("Tag");
	        $name = trim($_GET['tag']);
	        $Stat = $Tag->where('module="' . $this->getActionName() . '" and name="' . $name . '"')->field("id,count")->find();
	        $tagId = $Stat['id'];
	        $count = $Stat['count'];
	        // import("Think.Util.Page");
	        $p = new Page($count);
	        $Model = M($this->getActionName());
	        $Tagged = M("Tagged");
	        $recordIds = $Tagged->where("module='" . $this->getActionName() . "' and tag_id=" . $tagId)->getField('id,record_id');
	        if ($recordIds) {
	            $map['id'] = array('IN', $recordIds);
	            $this->_list($Model, $map);
	            $this->display('index');
	        } else {
	            $this->error('标签没有对应的文章！');
	        }
	    }
		
		/**
		 * 常用方法，检查权限
		 * @return boolean
		 * @param INT(USERID) $user
		 */
		protected function checkAccesslist($user){
			$access = $this->getAccessFun(); // 获得自己的权限
			$roleuser = $this->getTargetUser($user); //获得目标所在组
			
			foreach ($access as $key => $val){
				foreach ($roleuser as $a => $user){
					if ($val == $user['role_id']){
						return true;
					}else{
						return false;
					}
				}
			}
		}
		
		/**
		 * 常用方法，获得自己分组下的所有用户
		 * 
		 * @return array 
		 */
		protected function getGroupUserlist(){
			return $this->getAccessUserlist($this->getAccessFun());
		}
		
		private function getAccessFun(){
			$role_model = M('role_user');
			$role_model_group = M("role");
			
			$role_list = $role_model->where("user_id='".$_SESSION['authId']."'")->select();
			$role_id = 'tmp___';
			
			foreach ($role_list as $key=>$val){
			
				$user_group_list = $role_model_group->where("pid='".$val['role_id']."'")->select();
				foreach ($user_group_list as $g => $v) {
					$role_id .= ','.$v['id'];
					$group_son_list = $role_model_group->where("pid='".$v['id']."'")->select();
					if (!empty($group_son_list)){
						$role_id .= $this->getGrouplist($role_model_group, $v['id']);
					}
				}
			
			}
			$role_id = str_replace('tmp___,', '', $role_id);
			$role_array = explode(',',$role_id);
			return $role_array;
		}
		
		private function getTargetUser($UserID){
			$role_user_model = M('role_user');
			$role_list = $role_user_model->where("user_id='".$UserID."'")->select();
			return $role_list;
		}
		
		/**
		 * @return sting (2,10,3) 
		 * 取得自己所在组下的所有用户ID,将用户ID组合成字符串
		 * @param sting $IDlist (2,10,3)
		 */
		private function getAccessUserlist($IDlist){
			$model = M('role_user');
			
			$usermap['role_id'] = array('in',$IDlist);
			$list = $model->where($usermap)->select();
			$user_array = array();
			foreach ($list as $key => $val) {
				$user_array[$key] = $val['user_id'];
			}
			
			//return join(',', $user_array);
			return $user_array;
		}
		
		protected function getGrouplist($model,$pid){
			$rsid = '';
			$group_list = $model->where("pid='".$pid."'")->select();
			if (!empty($group_list)){
				foreach($group_list as $key=>$val){
					$rsid .= ','.$val['id'];
					$this->getGrouplist($model, $val['id']);
				}
			}
			return $rsid;
		}
		
		public function checkSession(){
			if ( isset( $_SESSION["crop_zoom"] ) ){
				if ( file_exists( $_SESSION["crop_zoom"]['large_path'] ) ){
					@unlink( $_SESSION["crop_zoom"]['large_path'] );
				}
				unset( $_SESSION["crop_zoom"] );
			}
		}
		
		//获取Select option分类列表
		public function getCategoryOption($type,$curID=0,$this_model=''){
			
			if (empty($this_model)){
				$this_model = 'Category';
			}
			
			$categroy_model = M( $this_model );
			$category_list = $categroy_model->where("type='".$type."' AND (url is NULL OR url='')")->field('id,pid,name')->select();
			$category_html = '';
			
			import('ORG.Util.Trees');
			$tree = new tree($category_list);
			
			$str = "<option value=\$id \$selected>\$spacer \$name</option>";
			if ($curID != 0){
				$category_html .= $tree->getTreelist(0, $str, $curID);
			}else{
				$category_html .= $tree->getTreelist(0, $str);
			}
			$this->assign("option",$category_html);
		}
		
		
		protected function doafterAction(){
			if (isset($_SESSION['picture_list_file_id'])) {
				unset($_SESSION['picture_list_file_id']);
			}
			if (isset($_SESSION['picture_list_file'])) {
				unset($_SESSION['picture_list_file']);
			}
			S('up_cache_'.$_SESSION['lastLoginTime'],NULL);
		}
		
		
		/*
		 * ====================================================
		 * 文档以及图集公用删除方法
		 * 
		 * ====================================================
		 */
		protected function eDelete( $type, $id ){
			$model = D( 'Archives' );
			$catelog = $model->where("id='".$id."'")->getField('cid');
			$return = 0;
			switch ( $type ){
				case 'picture' : 
					$p_model = D('picture');
					$p_list = $p_model->where("cid='".$id."'")->select();
					foreach ( $p_list as $key => $val ){
						$file_path = './' . C('WEB_PUBLIC_PATH') . '/' . C('DIR_UPLOAD_PATH') . '/' . $val['folder'] . '/';
						if ( file_exists( $file_path  ) ){
							@unlink( $file_path . $val['file'] );
							@unlink( $file_path . 'resize_' . $val['file'] );
							@unlink( $file_path . 'mini_' . $val['file'] );
							@unlink( $file_path . 'thumb_' . $val['file'] );
						}
					}
					$p_model->where("cid='".$id."'")->delete(); //删除图片数据
					$model->where("id='".$id."'")->delete();
					$return = 1;
					break;
					
				case 'archives' :
					$archives = $model->where("id='".$id."'")->field('thumb,content_attachment')->find();
					$this->checkDelAttach( $archives['content_attachment'] );
					$this->checkDelThumb( $archives['thumb'] );
					$model->where("id='".$id."'")->delete();
					$return = 1;
					break;
					
				case 'video' :
					$archives = $model->where("id='".$id."'")->field('thumb,content_attachment,video_path')->find();
					$this->checkDelAttach( $archives['content_attachment'] );
					$this->checkDelThumb( $archives['thumb'] );
					@unlink ( './' . C('WEB_PUBLIC_PATH') . '/' . C('DIR_ATTCH_PATH') . '/' . $archives['video_path'] );
					$model->where("id='".$id."'")->delete();
					$return = 1;
					break;
					
			}
			
			if ( $return == 0 ){
				$this->error( '删除失败！' );
			}else{
				D('Category')->where("id='".$catelog."'")->setDec('count'); //更新分类内容数目
				$this->success( '删除完成' );
			}
			
		}
		
		private function checkDelThumb( $file ){
			if ( !empty( $file ) ){
				$mini_file = str_replace( 'thumb_' , 'mini_', $file );
				@unlink ( './' . C('WEB_PUBLIC_PATH') . '/' . C('DIR_ATTCH_PATH') . '/' . $file );
				@unlink ( './' . C('WEB_PUBLIC_PATH') . '/' . C('DIR_ATTCH_PATH') . '/' . $mini_file );
			}
		}
		
		private function checkDelAttach( $file ){
			if ( !empty( $file ) ){
				$file_array = explode( '|', $file );
				if ( !empty( $file_array ) ){
					foreach ( $file_array as $key => $val ){
						unlink( '.' . $val );
					}
				}else{
					unlink( '.' . $file );
				}
			}
		}
		
		
		
	}
	
?>